const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

// Load environment variables
dotenv.config();

// Create Express app
const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// 创建上传目录
const fs = require('fs');
const uploadDir = path.join(__dirname, 'uploads');
const exportDir = path.join(__dirname, 'exports');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}
if (!fs.existsSync(exportDir)) {
  fs.mkdirSync(exportDir, { recursive: true });
}

// Swagger配置
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'WMS仓库管理系统 API',
      version: '1.0.0',
      description: 'WMS仓库管理系统的RESTful API文档',
    },
    servers: [
      {
        url: `http://localhost:${PORT}`,
        description: '开发服务器',
      },
    ],
    components: {
      schemas: {
        Location: {
          type: 'object',
          properties: {
            id: {
              type: 'integer',
              description: '货位ID'
            },
            location_code: {
              type: 'string',
              description: '货位编码'
            },
            aisle: {
              type: 'string',
              description: '巷道'
            },
            row: {
              type: 'string',
              description: '排'
            },
            column: {
              type: 'string',
              description: '列'
            },
            level: {
              type: 'string',
              description: '层'
            },
            status: {
              type: 'string',
              description: '状态(enabled/disabled)'
            },
            created_at: {
              type: 'string',
              format: 'date-time',
              description: '创建时间'
            },
            updated_at: {
              type: 'string',
              format: 'date-time',
              description: '更新时间'
            }
          }
        },
        Goods: {
          type: 'object',
          properties: {
            id: {
              type: 'integer',
              description: '货物ID'
            },
            name: {
              type: 'string',
              description: '货物名称'
            },
            sku: {
              type: 'string',
              description: 'SKU编码'
            },
            quantity: {
              type: 'integer',
              description: '数量'
            },
            location: {
              type: 'string',
              description: '货位'
            },
            status: {
              type: 'string',
              description: '状态'
            },
            batch_number: {
              type: 'string',
              description: '批次号'
            },
            expiry_date: {
              type: 'string',
              format: 'date',
              description: '过期日期'
            },
            specification: {
              type: 'string',
              description: '规格'
            },
            unit: {
              type: 'string',
              description: '单位'
            },
            created_at: {
              type: 'string',
              format: 'date-time',
              description: '创建时间'
            },
            updated_at: {
              type: 'string',
              format: 'date-time',
              description: '更新时间'
            }
          }
        },
        InboundDocument: {
          type: 'object',
          properties: {
            id: {
              type: 'integer',
              description: '入库单据ID'
            },
            goods_id: {
              type: 'integer',
              description: '货物ID'
            },
            supplier: {
              type: 'string',
              description: '供应商'
            },
            quantity: {
              type: 'integer',
              description: '数量'
            },
            expected_arrival_date: {
              type: 'string',
              format: 'date',
              description: '预计到达日期'
            },
            actual_arrival_date: {
              type: 'string',
              format: 'date',
              description: '实际到达日期'
            },
            status: {
              type: 'string',
              description: '状态'
            },
            operator: {
              type: 'string',
              description: '操作员'
            },
            notes: {
              type: 'string',
              description: '备注'
            },
            created_at: {
              type: 'string',
              format: 'date-time',
              description: '创建时间'
            },
            updated_at: {
              type: 'string',
              format: 'date-time',
              description: '更新时间'
            }
          }
        },
        OutboundDocument: {
          type: 'object',
          properties: {
            id: {
              type: 'integer',
              description: '出库单据ID'
            },
            goods_id: {
              type: 'integer',
              description: '货物ID'
            },
            customer: {
              type: 'string',
              description: '客户'
            },
            quantity: {
              type: 'integer',
              description: '数量'
            },
            expected_pickup_date: {
              type: 'string',
              format: 'date',
              description: '预计提货日期'
            },
            actual_pickup_date: {
              type: 'string',
              format: 'date',
              description: '实际提货日期'
            },
            status: {
              type: 'string',
              description: '状态'
            },
            operator: {
              type: 'string',
              description: '操作员'
            },
            notes: {
              type: 'string',
              description: '备注'
            },
            created_at: {
              type: 'string',
              format: 'date-time',
              description: '创建时间'
            },
            updated_at: {
              type: 'string',
              format: 'date-time',
              description: '更新时间'
            }
          }
        },
        Auth: {
          type: 'object',
          properties: {
            username: {
              type: 'string',
              description: '用户名'
            },
            password: {
              type: 'string',
              description: '密码'
            }
          }
        },
        AuthResponse: {
          type: 'object',
          properties: {
            success: {
              type: 'boolean',
              description: '是否成功'
            },
            message: {
              type: 'string',
              description: '消息'
            },
            data: {
              type: 'object',
              properties: {
                token: {
                  type: 'string',
                  description: 'JWT令牌'
                },
                user: {
                  type: 'object',
                  properties: {
                    id: {
                      type: 'integer',
                      description: '用户ID'
                    },
                    username: {
                      type: 'string',
                      description: '用户名'
                    },
                    role: {
                      type: 'string',
                      description: '角色'
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  apis: ['./src/routes/*.js', './src/controllers/*.js', './server.js'], // 指定包含API注释的文件路径
};

const swaggerDocs = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// Import auth middleware
const { login, register } = require('./src/middleware/auth');

// Import routes
const goodsRoutes = require('./src/routes/goodsRoutes');
const inboundRoutes = require('./src/routes/inboundRoutes');
const outboundRoutes = require('./src/routes/outboundRoutes');
const dataRoutes = require('./src/routes/dataRoutes');
const instructionRoutes = require('./src/modules/instruction/instructionRoutes');
const locationRoutes = require('./src/routes/locationRoutes');

// Import auth middleware
const { authenticateToken } = require('./src/middleware/auth');

// Import Instruction model to create table
const Instruction = require('./src/modules/instruction/Instruction');

// Create instruction table
Instruction.createTable((err) => {
  if (err) {
    console.error('创建指令表失败:', err.message);
  }
});

/**
 * @swagger
 * tags:
 *   name: Authentication
 *   description: 用户认证
 */

/**
 * @swagger
 * /api/auth/login:
 *   post:
 *     summary: 用户登录
 *     tags: [Authentication]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Auth'
 *     responses:
 *       200:
 *         description: 登录成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/AuthResponse'
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 用户名或密码错误
 *       500:
 *         description: 服务器错误
 */
// 认证路由
app.post('/api/auth/login', login);

/**
 * @swagger
 * /api/auth/register:
 *   post:
 *     summary: 用户注册
 *     tags: [Authentication]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               password:
 *                 type: string
 *                 description: 密码
 *               role:
 *                 type: string
 *                 description: 角色
 *     responses:
 *       201:
 *         description: 注册成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/AuthResponse'
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器错误
 */
app.post('/api/auth/register', register);

// Routes
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'modules.html'));
});

// 受保护的路由
app.use('/api/goods', authenticateToken, goodsRoutes);
app.use('/api/inbound', authenticateToken, inboundRoutes);
app.use('/api/outbound', authenticateToken, outboundRoutes);
app.use('/api/data', authenticateToken, dataRoutes);
app.use('/api/instructions', instructionRoutes);
app.use('/api/locations', authenticateToken, locationRoutes);

// Start server
app.listen(PORT, () => {
  console.log(`WMS System server running on port ${PORT}`);
  console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});

module.exports = app;